﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation; 
using System.Diagnostics;
using System.IO;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;

namespace XbdSoft.WPFVersion.AutoUpdate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Ctor
        public MainWindow()
        {
            InitializeComponent();
        }
        #endregion

        #region Load
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                DownloadFile();                
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("更新失败:{0}",ex.Message));
            }
        }
        #endregion

        #region Properties
        public string ExeInstallUrl { get; set; }
        private string TempSaveFilePath = string.Empty;
        #endregion

        #region Helper Methods

        private void DownloadFile()
        {
            MainProgressBar.Value = 0;
            MainTip.Text = "正在下载新的程序包......";
            try
            {
                if (String.IsNullOrEmpty(ExeInstallUrl))
                {
                    throw new ArgumentNullException("找不到安装文件的路径。");
                }
                var filename = Path.GetFileName(ExeInstallUrl);

                //下载文件存放在临时文件夹中 
                var tempPath = Path.Combine(Environment.CurrentDirectory, "Temp");
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                TempSaveFilePath = tempPath + @"\" + Guid.NewGuid().ToString("N") + filename;

                //if (File.Exists(ExeInstallUrl))
                //{
                //    File.Copy(ExeInstallUrl, TempSaveFilePath);
                //    UnZipFile();
                //    OpenUpdatedExe();
                //}
                //else
                {
                    WebClient client = new WebClient();
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                    client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
                    client.DownloadFileAsync(new Uri(ExeInstallUrl), TempSaveFilePath);
                }
            }
            catch (Exception ex)
            {
                WriteLog("更新失败：下载的文件名为空！");
            }
            finally
            {
                
            }
            MainTip.Text = "下载新的程序包完毕";
        }

        void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            UnZipFile();
            OpenUpdatedExe();
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            MainProgressBar.Value = e.ProgressPercentage;
        }

        private void UnZipFile()
        {
            MainTip.Text = "正在解压程序文件......";
            try
            {
                WriteLog(TempSaveFilePath);

                MainProgressBar.Value = 0;
                using (ZipInputStream zis = new ZipInputStream(File.OpenRead(TempSaveFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = zis.GetNextEntry()) != null)
                    {
                        try
                        {
                            MainProgressBar.Value = zis.Length == 0 ? 100 : zis.Position * 100.0 / zis.Length;

                            string directoryName = Environment.CurrentDirectory;
                            string zipfilename = System.IO.Path.GetFileName(theEntry.Name);
                            string fileFullName = Path.Combine(directoryName, zipfilename);

                            if (directoryName.Length > 0 && !Directory.Exists(directoryName))
                            {
                                Directory.CreateDirectory(directoryName);
                            }

                            if (fileFullName != String.Empty)
                            {
                                if (File.Exists(fileFullName))
                                    File.Delete(fileFullName);

                                using (FileStream streamWriter = File.Create(fileFullName))
                                {
                                    int size = 2048;
                                    byte[] data = new byte[2048];
                                    while (true)
                                    {
                                        size = zis.Read(data, 0, data.Length);
                                        if (size > 0)
                                        {
                                            streamWriter.Write(data, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                }

            }
            catch(Exception ex)
            {
                MainTip.Text = "解压程序包失败！";
                WriteLog("解压程序包失败！"+ex.Message);
            }
            MainTip.Text = "解压程序文件完毕";
        }

        private void OpenUpdatedExe()
        {
            MainTip.Text = "等待打开新程序...";
            try
            {
                Thread.Sleep(1000);
                Process openupdatedexe = new Process();
                openupdatedexe.StartInfo.FileName = System.IO.Path.Combine(Environment.CurrentDirectory, App.ExeProcessName);
                openupdatedexe.Start();
                if (File.Exists(TempSaveFilePath))
                    File.Delete(TempSaveFilePath);
                Process.GetCurrentProcess().Kill();
            }
            catch
            {
                WriteLog("打开新程序失败！");
            }
        }

        private void WriteLog(string str)  
        {    
            string strLog = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + str + "\r\n";    
            StreamWriter errorlog = new StreamWriter(System.IO.Path.Combine(Environment.CurrentDirectory, @"log.txt"), true);  
            errorlog.Write(strLog);  
            errorlog.Flush();  
            errorlog.Close();  
        }  

        #endregion
    }
}
